import router from "@/router";
import axios, { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000
});

service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.headers["Content-Type"] = "application/json";
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const status = response.data.code || response.status;
    const message = response.data.msg;
    if (status === 200) {
      return response.data;
    }
    if (status === 401 || status === 421) {
      ElMessageBox.confirm("您尚未登录或者登录信息已失效，请重新登录", "请登录", {
        confirmButtonText: "前往登录",
        type: "warning"
      }).then(() => {
        localStorage.clear();
        router.push("/login");
      });
    } else {
      ElMessage({
        type: "error",
        message: message
      });
    }
    return Promise.reject(new Error(message));
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

export default service;
